import { Button, Input, message, Modal, Form, Typography } from "antd";
import { EyeInvisibleOutlined, EyeOutlined, LockOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import { useState, useEffect } from "react";

const { Text } = Typography;

const EditPasswordModal = (props) => {
    const { editPasswordParam, setEditPasswordParam } = props;
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [passwordStrength, setPasswordStrength] = useState(0);

    // 当模态框显示状态变化时重置表单
    useEffect(() => {
        if (editPasswordParam.visible) {
            // 模态框打开时重置表单
            form.resetFields();
            setPasswordStrength(0);
        }
    }, [editPasswordParam.visible, form]);

    /**
     * 安全关闭模态框
     */
    const closeEditPasswordModal = () => {
        // 只更新外部状态，避免内部状态同步导致的循环
        setEditPasswordParam(prev => ({
            ...prev,
            visible: false
        }));
        // 重置表单（使用setTimeout避免在状态更新期间操作表单）
        setTimeout(() => {
            try {
                form.resetFields();
                setPasswordStrength(0);
            } catch (err) {
                console.warn("表单重置失败:", err);
            }
        }, 0);
    };

    /**
     * 评估密码强度
     */
    const evaluatePasswordStrength = (password) => {
        if (!password) {
            setPasswordStrength(0);
            return 0;
        }

        let strength = 0;
        if (password.length >= 8) strength++;
        if (/[a-z]/.test(password)) strength++;
        if (/[A-Z]/.test(password)) strength++;
        if (/[0-9]/.test(password)) strength++;
        if (/[^a-zA-Z0-9]/.test(password)) strength++;

        setPasswordStrength(strength);
        return strength;
    };

    /**
     * 获取密码强度文本
     */
    const getStrengthText = () => {
        const texts = ["弱", "中", "较强", "强", "极强"];
        const colors = ["text-red-500", "text-orange-500", "text-yellow-500", "text-blue-500", "text-green-500"];
        return <span className={colors[passwordStrength]}>{texts[passwordStrength]}</span>;
    };

    /**
     * 修改密码
     */
    const doEditPassword = async () => {
        try {
            const values = await form.validateFields();

            if (evaluatePasswordStrength(values.newPassword) < 2) {
                messageApi.warning("密码强度不足，请使用更复杂的密码");
                return;
            }

            setLoading(true);

            await RequestUtils.post(Apis.user.editPassword, {
                id: editPasswordParam.userInfo.userId,
                oldPassword: values.oldPassword,
                newPassword: values.newPassword
            });

            messageApi.success("修改密码成功，请重新登录");
            closeEditPasswordModal();

            setTimeout(() => {
                RequestUtils.post(Apis.user.userQuit, { clientType: "pc" })
                    .finally(() => {
                        RequestUtils.clearToken();
                        window.location.replace("/login");
                    });
            }, 2000);
        } catch (err) {
            if (err.errorFields) return; // 忽略表单验证错误
            messageApi.error(`修改密码失败: ${err.message || "未知错误"}`);
        } finally {
            setLoading(false);
        }
    };

    // 防止在渲染期间触发状态更新
    const handlePasswordChange = (e) => {
        evaluatePasswordStrength(e.target.value);
    };

    return (
        <Modal
            title={<div className="flex items-center">
                <LockOutlined className="mr-2 text-primary" />
                <span>修改用户密码</span>
            </div>}
            visible={editPasswordParam.visible}
            onCancel={closeEditPasswordModal}
            maskClosable={true}
            destroyOnClose={true}
            footer={[
                <Button
                    key="cancel"
                    danger
                    onClick={closeEditPasswordModal}
                >
                    取消
                </Button>,
                <Button
                    key="submit"
                    type="primary"
                    onClick={doEditPassword}
                    loading={loading}
                >
                    确认修改
                </Button>
            ]}
        >
            {contextHolder}
            <Form
                form={form}
                layout="vertical"
                name="editPasswordForm"
                initialValues={{
                    oldPassword: "",
                    newPassword: "",
                    confirmPassword: ""
                }}
            >
                <Form.Item
                    name="oldPassword"
                    label="旧密码"
                    rules={[{ required: true, message: "请输入旧密码" }]}
                >
                    <Input.Password
                        placeholder="请输入当前使用的密码"
                        iconRender={visible => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                    />
                </Form.Item>

                <Form.Item
                    name="newPassword"
                    label="新密码"
                    rules={[
                        { required: true, message: "请输入新密码" },
                        { min: 8, message: "密码长度不能少于8位" },
                        { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: "密码必须包含字母和数字" }
                    ]}
                >
                    <Input.Password
                        placeholder="请输入新密码（至少8位，包含字母和数字）"
                        iconRender={visible => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                        onChange={handlePasswordChange}
                    />
                </Form.Item>

                <div className="mb-4 px-1">
                    <div className="flex justify-between text-sm mb-1">
                        <span>密码强度：</span>
                        <span>{getStrengthText()}</span>
                    </div>
                    <div className="h-1.5 w-full bg-gray-200 rounded-full overflow-hidden">
                        <div
                            className="h-full transition-all duration-300 ease-out"
                            style={{
                                width: `${passwordStrength * 20}%`,
                                backgroundColor: passwordStrength >= 3 ? '#52c41a' :
                                    passwordStrength >= 2 ? '#1890ff' :
                                        passwordStrength >= 1 ? '#faad14' : '#f5222d'
                            }}
                        />
                    </div>
                </div>

                <Form.Item
                    name="confirmPassword"
                    label="确认新密码"
                    rules={[
                        { required: true, message: "请再次输入新密码" },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (!value || getFieldValue('newPassword') === value) {
                                    return Promise.resolve();
                                }
                                return Promise.reject(new Error('两次输入的密码不一致'));
                            },
                        }),
                    ]}
                >
                    <Input.Password
                        placeholder="请再次输入新密码"
                        iconRender={visible => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                    />
                </Form.Item>

                <div className="mt-2 p-3 bg-blue-50 rounded-md border border-blue-100 flex items-start">
                    <ExclamationCircleOutlined className="text-blue-500 mt-0.5 mr-2" />
                    <Text type="secondary" className="text-sm">
                        密码修改成功后，您需要重新登录系统。请牢记您的新密码。
                    </Text>
                </div>
            </Form>
        </Modal>
    );
};

export default EditPasswordModal;
